package datasource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import play.mvc.Controller;
/**
 * 本机测试用的
 *
 *
 * @version 1.0
 * @since JDK1.7
 * @author yutao
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2017年4月28日下午3:54:33
 */
public class ConnectionSSH extends Controller {

	private static class ConnectionSSHClass{
		private static final Session session = getSessionInstance();
	}
	
	public static Session getSessionInstance(){
		Session session = null;
		String pubKeyPath = "C:\\Users\\yutao\\.ssh\\id_rsa";
		String host = "192.168.0.110";
		int port = 22;
		String username = "root";
		JSch jsch = new JSch();
		try {
			jsch.addIdentity(pubKeyPath);
			session = jsch.getSession(username, host, port);//为了连接做准备
	        session.setConfig("StrictHostKeyChecking", "no");
//	        session.setTimeout(3000);
	        session.connect();
		} catch (JSchException e) {
			e.printStackTrace();
		}
		return session;
	}
	
	
	public static final Session getSession(){
//		System.out.println(ConnectionSSHClass.session.isConnected());
		return ConnectionSSHClass.session;
	}
	
	public static void main(String[] args) throws JSchException, IOException {
		JSch jsch = new JSch();
        String pubKeyPath = "C:\\Users\\yutao\\.ssh\\id_rsa";
        jsch.addIdentity(pubKeyPath);

        String username = "root";
        String host = "192.168.0.110";
        Session session=jsch.getSession(username, host, 22);//为了连接做准备
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        String command = "ls";
        ChannelExec channel= (ChannelExec)session.openChannel("exec");  
        channel.setCommand(command);
        command="ls -l";
        channel.setCommand(command);
        channel.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        String msg;
		while ((msg = in.readLine()) != null) {
			System.out.println(msg);
		}

		channel.disconnect();
		session.disconnect();
	}
	
}
